package org.cary.lucene;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

import org.cary.lucene.search.LuceneSearchEngine;
import org.cary.utils.StringUtils;
import org.cary.utils.TaskEngine;

/**
 * 异步管理搜索索引
 * @author cary
 */
public class IndexQueueManager {

	private static IndexQueueManager indexManager = new IndexQueueManager();
	// 消费时间间隔，默认是30秒
	private static long luceneConsumerPeriod = 3;// UserProperties.getLuceneConsumerPeriod();

	// 消息缓存区
	private static BlockingQueue<StoreQueueBean> storeBeanQueue = null;
	private static IndexQueueConsumer luceneConsumer = null;
	private static Future luceneConsumerFuture = null;

	// 是否使用mq当消费者
	private static boolean useMqConsumer = false;// UserProperties.isLuceneConsumerMq();
	private static boolean isStart = false;

	private IndexQueueManager() {
	}

	public static IndexQueueManager getInstance() {
		return indexManager;
	}

	public static void start() {
		if (!isStart) {
			isStart = true;
			storeBeanQueue = new LinkedBlockingQueue<StoreQueueBean>();
			luceneConsumer = new IndexQueueConsumer(storeBeanQueue, luceneConsumerPeriod);

			TaskEngine engine = TaskEngine.getInstance();
			luceneConsumerFuture = engine.submit(luceneConsumer);
		}
	}

	public static void stop() {
		if (isStart) {
			// 停止后台时间任务
			luceneConsumer.stopTimerTask();
			// 关闭自己的服务
			luceneConsumerFuture.cancel(false);
			isStart = false;
		}
	}

	public void put(StoreQueueBean queueBean) {
		try {
			storeBeanQueue.put(queueBean);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除索引
	 * @param share
	 */
	public void indexDeleted(String indexId) {
		try {
			if (StringUtils.isBlank(indexId)) return;
			StoreQueueBean queueBean = new StoreQueueBean(LuceneSearchEngine.INDEX_DELETE);
			queueBean.setId(indexId);
			if (useMqConsumer) {
				// ActiveMqManage.sendLuceneMessage(queueBean);
			} else {
				put(queueBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 方法介绍 增加共享搜索,这个是V2新版本的共享规则
	 * @param sharing
	 * @param operateType
	 * @author cary
	 */
	public void indexChanged(StoreQueueBean queueBean, int operateType) {
		try {
			if (queueBean == null) return;
			if (useMqConsumer) {
				// ActiveMqManage.sendLuceneMessage(queueBean);
			} else {
				put(queueBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
